﻿using MicroMvvm;
using Microsoft.Practices.Unity;
using ModernUILogViewer.Business;
using ModernUILogViewer.Model;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Input;

namespace ModernUILogViewer.ViewModel
{
    public class OptionsViewModel : BaseViewModel    
    {
        #region Constructor

        public OptionsViewModel(MainViewModel mainVM)
        {
            this.mainVM = mainVM;

            //LineBeginningRegExp = @"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}";
            //DateRegExp = @"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}";
            //DateFormat = "yyyy-MM-dd HH:mm:ss";
            //LevelRegExp = @"(DEBUG|INFO|WARN|ERROR|FATAL).*\s\-\s";

            //LevelGroupMatch = 1;

        }
        
        #endregion
        
        #region EventHandler

        public event EventHandler ImportSettingsEventException;
        public event EventHandler ExportSettingsSuccessfulEvent;

        //public event EventHandler SettingsSaved;
        //public event EventHandler SettingsReloaded;

        //public event EventHandler EventLinePatternException;
        //public event EventHandler EventDatePatternException;
        //public event EventHandler EventLevelPatternException;

        #endregion

        #region Fields

        private MainViewModel mainVM;

        #endregion

        #region Properties

        private CultureInfo selectedCultureInfo;

        public CultureInfo SelectedCultureInfo
        {
            get { return selectedCultureInfo; }
            set
            {
                selectedCultureInfo = value;
                RaisePropertyChanged(() => SelectedCultureInfo);
            }
        }        

        private bool includeDateMatch;

        public bool IncludeDateMatch
        {
            get { return includeDateMatch; }
            set { 
                includeDateMatch = value;                
                RaisePropertyChanged(() => IncludeDateMatch);
            }
        }

        private bool includeLevelMatch;

        public bool IncludeLevelMatch
        {
            get { return includeLevelMatch; }
            set
            {
                includeLevelMatch = value;
                RaisePropertyChanged(() => IncludeLevelMatch);
            }
        }

        private int dateGroupMatch;

        public int DateGroupMatch
        {
            get { return dateGroupMatch; }
            set { 
                dateGroupMatch = value;
                RaisePropertyChanged(() => DateGroupMatch);
            }
        }

        private int levelGroupMatch;

        public int LevelGroupMatch
        {
            get { return levelGroupMatch; }
            set { 
                levelGroupMatch = value;
                RaisePropertyChanged(() => LevelGroupMatch);
            }
        }
        

        private string dateFormat;

        public string DateFormat
        {
            get { return dateFormat; }
            set { 
                dateFormat = value;
                RaisePropertyChanged(() => DateFormat);
            }
        }

        private string lineBeginningRegExp;

        public string LineBeginningRegExp
        {
            get { return lineBeginningRegExp; }
            set { 
                lineBeginningRegExp = value;
                RaisePropertyChanged(() => LineBeginningRegExp);
            }
        }

        private string dateRegExp;

        public string DateRegExp
        {
            get { return dateRegExp; }
            set { 
                dateRegExp = value;
                RaisePropertyChanged(() => DateRegExp);
            }
        }

        private string levelRegExp;

        public string LevelRegExp
        {
            get { return levelRegExp; }
            set { 
                levelRegExp = value;
                RaisePropertyChanged(() => LevelRegExp);
            }
        }        
        
        #endregion

        #region Methods
        
        //void SaveColorSettingsExecuted()
        //{
        //    MessengerProvider.Instance.NotifyColleagues(MessengerEvents.MSG_COLOR_SETTINGS_SAVED);

        //    RaiseEventInvoker(SettingsSaved);
        //}

        //void ReloadColorSettingsExecuted()
        //{
        //    MessengerProvider.Instance.NotifyColleagues(MessengerEvents.MSG_COLOR_SETTINGS_RELOADED);

        //    RaiseEventInvoker(SettingsSaved);
        //}

        //void SaveRegexSettingsExecuted()
        //{
        //    MessengerProvider.Instance.NotifyColleagues(MessengerEvents.MSG_REGEX_SETTINGS_SAVED, this);

        //    RaiseEventInvoker(SettingsSaved);
        //}            //string file = SaveFile("Ini (*.ini)|*.ini");

        //void ReloadRegexSettingsExecuted()
        //{
        //    MessengerProvider.Instance.NotifyColleagues(MessengerEvents.MSG_REGEX_SETTINGS_RELOADED, this);

        //    RaiseEventInvoker(SettingsReloaded);
        //}

        void ExportSettingsExecute()
        {
            //string file = OpenSaveFileDlg("Ini (*.ini)|*.ini");

            IUnityContainer container = UnityContainerProvider.Instance;
            IDialogService service = container.Resolve<IDialogService>(DialogServiceNS.DLG_OPEN_SAVE_INI_FILE);

            string file = service.SaveFile();

            if (String.IsNullOrEmpty(file) == false)
            {
                File.Create(file).Dispose();

                IConfigSource configSource = new IniConfigSource(file);

                IConfig configSectionPattern = configSource.Configs.Add("Pattern");
                IConfig configSectionGeneral = configSource.Configs.Add("General");

                configSectionPattern.Set("linebeginpattern", lineBeginningRegExp);
                configSectionGeneral.Set("includedate", includeDateMatch);
                configSectionGeneral.Set("includelevel", includeLevelMatch);
                configSectionPattern.Set("datepattern", dateRegExp);
                configSectionPattern.Set("loglevelpattern", levelRegExp);
                configSectionGeneral.Set("dateformat", dateFormat);
                configSectionGeneral.Set("dategroup", dateGroupMatch);
                configSectionGeneral.Set("levelgroup", levelGroupMatch);
                configSectionGeneral.Set("culture", selectedCultureInfo);

                configSource.Save();

                RaiseEventInvoker(ExportSettingsSuccessfulEvent);
            }
            
        }

        void ImportSettingsExecute()
        {
            IUnityContainer container = UnityContainerProvider.Instance;
            IDialogService service = container.Resolve<IDialogService>(DialogServiceNS.DLG_OPEN_SAVE_INI_FILE);

            string[] files = service.OpenFile(false);

            if (files.Length > 0)
            {
                string file = files[0];

                try
                {
                    ImportSettingsFromFile(file);
                }
                catch (Exception)
                {
                    RaiseEventInvoker(ImportSettingsEventException);
                }
                
            }
        }

        public void ImportSettingsFromFile(string file)
        {

            try
            {
                IConfigSource configSource = new IniConfigSource(file);

                IConfig configSectionPattern = configSource.Configs["Pattern"];
                IConfig configSectionGeneral = configSource.Configs["General"];

                LineBeginningRegExp = configSectionPattern.Get("linebeginpattern");
                IncludeDateMatch = Boolean.Parse(configSectionGeneral.Get("includedate", "true"));
                IncludeLevelMatch = Boolean.Parse(configSectionGeneral.Get("includelevel", "true"));
                DateRegExp = configSectionPattern.Get("datepattern");
                LevelRegExp = configSectionPattern.Get("loglevelpattern");
                DateFormat = configSectionGeneral.Get("dateformat");
                DateGroupMatch = Int32.Parse(configSectionGeneral.Get("dategroup", "0"));
                LevelGroupMatch = Int32.Parse(configSectionGeneral.Get("levelgroup", "0"));
                SelectedCultureInfo = new CultureInfo(configSectionGeneral.Get("culture", "en"));
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region Commands
        
        //public ICommand SaveColorSettings { get { return new RelayCommand(SaveColorSettingsExecuted); } }
        //public ICommand ReloadColorSettings { get { return new RelayCommand(ReloadColorSettingsExecuted); } }
        //public ICommand SaveRegexSettings { get { return new RelayCommand(SaveRegexSettingsExecuted); } }
        //public ICommand ReloadRegexSettings { get { return new RelayCommand(ReloadRegexSettingsExecuted); } }
        public ICommand ImportSettings { get { return new MvvmFoundation.Wpf.RelayCommand(ImportSettingsExecute); } }
        public ICommand ExportSettings { get { return new MvvmFoundation.Wpf.RelayCommand(ExportSettingsExecute); } }

        #endregion
    }
}
